package com.sky.filter;

import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.Employee;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 陈烨庆
 * @version 1.0
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserDetailsService employeeUserDetailsService;

    @Autowired
    private UserDetailsService userUserDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("当前线程的id：{}", Thread.currentThread().getId());

        //1、从请求头中获取令牌
        String adminToken = request.getHeader(jwtProperties.getAdminTokenName());
        String userToken = request.getHeader(jwtProperties.getUserTokenName());

        if (StringUtils.hasText(adminToken)) {
            //2、校验令牌
            log.info("jwt校验:{}", adminToken);
            Claims claims = null;
            try {
                claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), adminToken);
                Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
                String username = claims.get(JwtClaimsConstant.USERNAME).toString();
                if (StringUtils.hasText(username)) {
                    Employee employee = (Employee) employeeUserDetailsService.loadUserByUsername(username);
                    if (!ObjectUtils.isEmpty(employee)) {
                        // 生成SpringSecurity的通过认证标识
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(employee, null, employee.getAuthorities());

                        // 放到SpringSecurity的上下文
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            } catch (Exception e) {
                log.info("token解析失败");
            }
        }
        if (StringUtils.hasText(userToken)) {
            //2、校验令牌
            log.info("jwt校验:{}", userToken);
            Claims claims = null;
            try {
                claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), userToken);
                Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
                String openId = claims.get(JwtClaimsConstant.OPEN_ID).toString();
                if (StringUtils.hasText(openId)) {
                    User user = (User) userUserDetailsService.loadUserByUsername(openId);
                    if (!ObjectUtils.isEmpty(user)) {
                        // 生成SpringSecurity的通过认证标识
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

                        // 放到SpringSecurity的上下文
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            } catch (Exception e) {
                log.info("token解析失败");
            }
        }
        filterChain.doFilter(request, response);
    }
}
